<template>
  <view class="container">
    <!-- 页面头部标题 -->
    <view class="page-header">
      <view class="back-button" @click="goBack">
        <u-icon name="arrow-left" size="36" color="#ffffff"></u-icon>
      </view>
      <view class="header-title">扫码结果</view>
    </view>

    <!-- 结果内容 -->
    <view class="result-container">
      <!-- 成功图标 -->
      <view class="success-icon">
        <u-icon name="checkmark-circle" size="120" color="#00b894"></u-icon>
      </view>

      <!-- 结果信息 -->
      <view class="result-info">
        <view class="result-title">扫码成功</view>
        <view class="result-subtitle">识别到以下内容：</view>
      </view>

      <!-- 结果内容卡片 -->
      <view class="result-card">
        <view class="card-header">
          <view class="content-type">{{ getContentType() }}</view>
          <view class="scan-time">{{ scanTime }}</view>
        </view>
        <view class="card-content">
          <text class="content-text" @longpress="copyText">{{
            scanResult
          }}</text>
        </view>
        <view class="card-actions">
          <view class="action-item" @click="copyText">
            <u-icon name="copy" size="32" color="#74b9ff"></u-icon>
            <text class="action-text">复制</text>
          </view>
          <view v-if="isUrl" class="action-item" @click="openUrl">
            <u-icon name="external-link" size="32" color="#74b9ff"></u-icon>
            <text class="action-text">打开链接</text>
          </view>
          <view class="action-item" @click="shareResult">
            <u-icon name="share" size="32" color="#74b9ff"></u-icon>
            <text class="action-text">分享</text>
          </view>
        </view>
      </view>

      <!-- 操作建议 -->
      <view class="suggestion-card" v-if="suggestion">
        <view class="suggestion-title">操作建议</view>
        <view class="suggestion-content">{{ suggestion }}</view>
        <view
          v-if="suggestedAction"
          class="suggestion-action"
          @click="handleSuggestedAction"
        >
          {{ suggestedAction }}
        </view>
      </view>

      <!-- 历史记录 -->
      <view class="history-card">
        <view class="history-header">
          <view class="history-title">最近扫码</view>
          <view class="clear-history" @click="clearHistory">清空</view>
        </view>
        <view v-if="scanHistory.length > 0" class="history-list">
          <view
            v-for="(item, index) in scanHistory"
            :key="index"
            class="history-item"
            @click="selectHistoryItem(item)"
          >
            <view class="history-content">{{
              getShortContent(item.content)
            }}</view>
            <view class="history-time">{{ formatTime(item.time) }}</view>
          </view>
        </view>
        <view v-else class="history-empty">暂无扫码记录</view>
      </view>

      <!-- 底部按钮 -->
      <view class="bottom-actions">
        <view class="action-btn secondary" @click="scanAgain">
          <u-icon name="scan" size="36" color="#666666"></u-icon>
          <text class="btn-text">重新扫码</text>
        </view>
        <view class="action-btn primary" @click="handleNextStep">
          <u-icon name="arrow-right" size="36" color="#ffffff"></u-icon>
          <text class="btn-text">下一步</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 扫码结果
      scanResult: "",
      // 扫码类型
      scanType: "default",
      // 扫码时间
      scanTime: "",
      // 扫码历史记录
      scanHistory: [],
    };
  },

  computed: {
    /**
     * 是否为URL
     */
    isUrl() {
      return /^https?:\/\//.test(this.scanResult);
    },

    /**
     * 操作建议
     */
    suggestion() {
      if (this.isUrl) {
        return "检测到网页链接，您可以点击下方按钮打开";
      } else if (this.scanResult.includes("RENTAL_CODE")) {
        return "检测到租用代码，点击确认开始租用设备";
      } else if (this.scanResult.includes("RETURN_CODE")) {
        return "检测到归还代码，点击确认归还设备";
      } else if (this.scanResult.includes("USER_ID")) {
        return "检测到用户ID，可以查看用户信息";
      }
      return "";
    },

    /**
     * 建议操作文本
     */
    suggestedAction() {
      if (this.isUrl) {
        return "打开链接";
      } else if (this.scanResult.includes("RENTAL_CODE")) {
        return "开始租用";
      } else if (this.scanResult.includes("RETURN_CODE")) {
        return "确认归还";
      } else if (this.scanResult.includes("USER_ID")) {
        return "查看用户";
      }
      return "";
    },

    /**
     * 主要操作按钮文本
     */
    primaryActionText() {
      if (this.suggestion) {
        return "确认操作";
      }
      return "完成";
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.scanResult = decodeURIComponent(options.result || "");

    console.log("options.result", {
      res: options.result,
      result: decodeURIComponent(options.result || ""),
    });

    this.scanType = options.type || "default";
    this.scanTime = this.getCurrentTime();

    // 保存到历史记录
    this.saveToHistory();

    // 加载历史记录
    this.loadHistory();
  },

  methods: {
    /**
     * 返回上一页
     */
    goBack() {
      uni.navigateBack({
        delta: 1,
      });
    },

    /**
     * 获取内容类型
     */
    getContentType() {
      if (this.isUrl) {
        return "网页链接";
      } else if (this.scanResult.includes("RENTAL_CODE")) {
        return "租用代码";
      } else if (this.scanResult.includes("RETURN_CODE")) {
        return "归还代码";
      } else if (this.scanResult.includes("USER_ID")) {
        return "用户ID";
      }
      return "文本内容";
    },

    /**
     * 获取当前时间
     */
    getCurrentTime() {
      const now = new Date();
      return now.toLocaleString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
      });
    },

    /**
     * 复制文本
     */
    copyText() {
      uni.setClipboardData({
        data: this.scanResult,
        success: () => {
          uni.showToast({
            title: "已复制到剪贴板",
            icon: "success",
          });
        },
      });
    },

    /**
     * 打开URL
     */
    openUrl() {
      if (this.isUrl) {
        // #ifdef H5
        window.open(this.scanResult, "_blank");
        // #endif

        // #ifdef MP-WEIXIN
        uni.showModal({
          title: "打开链接",
          content: "即将跳转到外部链接，是否继续？",
          success: (res) => {
            if (res.confirm) {
              // 微信小程序中打开网页
              uni.navigateTo({
                url: `/pages/webview/index?url=${encodeURIComponent(
                  this.scanResult
                )}`,
              });
            }
          },
        });
        // #endif
      }
    },

    /**
     * 分享结果
     */
    shareResult() {
      uni.share({
        provider: "weixin",
        type: 0,
        title: "扫码结果",
        summary: this.scanResult,
        success: () => {
          uni.showToast({
            title: "分享成功",
            icon: "success",
          });
        },
        fail: () => {
          // 复制作为备选方案
          this.copyText();
        },
      });
    },

    /**
     * 处理建议操作
     */
    handleSuggestedAction() {
      if (this.isUrl) {
        this.openUrl();
      } else if (this.scanResult.includes("RENTAL_CODE")) {
        this.handleRentalCode();
      } else if (this.scanResult.includes("RETURN_CODE")) {
        this.handleReturnCode();
      } else if (this.scanResult.includes("USER_ID")) {
        this.handleUserCode();
      }
    },

    /**
     * 处理租用代码
     */
    handleRentalCode() {
      // 跳转到支付页面
      uni.navigateTo({
        url: `/pages/newpayment/index?code=${encodeURIComponent(
          this.scanResult
        )}&type=rental`,
      });
    },

    /**
     * 处理归还代码
     */
    handleReturnCode() {
      // 跳转到订单详情页面
      uni.navigateTo({
        url: `/pages/newreturn/index?code=${encodeURIComponent(
          this.scanResult
        )}&type=return`,
      });
    },

    /**
     * 处理用户代码
     */
    handleUserCode() {
      const userId = this.scanResult.replace("USER_ID_", "");
      uni.navigateTo({
        url: `/pages/user/detail?userId=${userId}`,
      });
    },

    /**
     * 处理主要操作
     */
    handlePrimaryAction() {
      if (this.suggestion) {
        this.handleSuggestedAction();
      } else {
        this.goBack();
      }
    },

    /**
     * 重新扫码
     */
    scanAgain() {
      uni.navigateBack({
        delta: 1,
      });
    },

    /**
     * 保存到历史记录
     */
    saveToHistory() {
      try {
        let history = uni.getStorageSync("scan_history") || [];

        // 避免重复记录
        history = history.filter((item) => item.content !== this.scanResult);

        // 添加新记录到开头
        history.unshift({
          content: this.scanResult,
          time: Date.now(),
          type: this.scanType,
        });

        // 限制历史记录数量
        if (history.length > 20) {
          history = history.slice(0, 20);
        }

        uni.setStorageSync("scan_history", history);
      } catch (error) {
        console.error("保存历史记录失败:", error);
      }
    },

    /**
     * 加载历史记录
     */
    loadHistory() {
      try {
        const history = uni.getStorageSync("scan_history") || [];
        this.scanHistory = history.slice(0, 5); // 只显示最近5条
      } catch (error) {
        console.error("加载历史记录失败:", error);
        this.scanHistory = [];
      }
    },

    /**
     * 清空历史记录
     */
    clearHistory() {
      uni.showModal({
        title: "确认清空",
        content: "确定要清空所有扫码记录吗？",
        success: (res) => {
          if (res.confirm) {
            try {
              uni.removeStorageSync("scan_history");
              this.scanHistory = [];
              uni.showToast({
                title: "已清空",
                icon: "success",
              });
            } catch (error) {
              uni.showToast({
                title: "清空失败",
                icon: "none",
              });
            }
          }
        },
      });
    },

    /**
     * 选择历史记录项
     */
    selectHistoryItem(item) {
      this.scanResult = item.content;
      this.scanTime = this.formatTime(item.time);
    },

    /**
     * 获取短内容（用于历史记录显示）
     */
    getShortContent(content) {
      if (content.length > 30) {
        return content.substring(0, 30) + "...";
      }
      return content;
    },

    /**
     * 格式化时间
     */
    formatTime(timestamp) {
      const date = new Date(timestamp);
      const now = Date.now();
      const diff = now - timestamp;

      if (diff < 60000) {
        // 1分钟内
        return "刚刚";
      } else if (diff < 3600000) {
        // 1小时内
        return Math.floor(diff / 60000) + "分钟前";
      } else if (diff < 86400000) {
        // 1天内
        return Math.floor(diff / 3600000) + "小时前";
      } else {
        return date.toLocaleDateString("zh-CN");
      }
    },

    /**
     * 处理下一步操作
     */
    handleNextStep() {
      if (this.isUrl) {
        this.openUrl();
      } else if (this.scanResult.includes("RENTAL_CODE")) {
        this.handleRentalCode();
      } else if (this.scanResult.includes("RETURN_CODE")) {
        this.handleReturnCode();
      } else if (this.scanResult.includes("USER_ID")) {
        this.handleUserCode();
      }
    },
  },

  /**
   * 分享当前页面
   */
  onShareAppMessage() {
    return {
      title: "扫码结果",
      path: "/pages/newscanresult/index",
    };
  },
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #f8f9fa;
  padding-bottom: 120rpx;
}

.page-header {
  background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
  padding: 60rpx 40rpx 30rpx;
  display: flex;
  align-items: center;
  position: relative;

  .back-button {
    position: absolute;
    left: 40rpx;
    top: 50%;
    transform: translateY(-50%);
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.2);
  }

  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #ffffff;
    text-align: center;
    text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    flex: 1;
  }
}

.result-container {
  padding: 40rpx 30rpx;
}

.success-icon {
  text-align: center;
  margin-bottom: 30rpx;
}

.result-info {
  text-align: center;
  margin-bottom: 40rpx;

  .result-title {
    font-size: 40rpx;
    font-weight: 600;
    color: #333333;
    margin-bottom: 16rpx;
  }

  .result-subtitle {
    font-size: 28rpx;
    color: #666666;
  }
}

.result-card {
  background: #ffffff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .content-type {
      background: #74b9ff;
      color: #ffffff;
      font-size: 24rpx;
      padding: 8rpx 16rpx;
      border-radius: 12rpx;
    }

    .scan-time {
      font-size: 24rpx;
      color: #999999;
    }
  }

  .card-content {
    background: #f8f9fa;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;

    .content-text {
      font-size: 30rpx;
      color: #333333;
      line-height: 1.6;
      word-break: break-all;
    }
  }

  .card-actions {
    display: flex;
    justify-content: space-around;

    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20rpx;

      .action-text {
        font-size: 24rpx;
        color: #74b9ff;
        margin-top: 8rpx;
      }
    }
  }
}

.suggestion-card {
  background: #fff7e6;
  border: 1rpx solid #ffd666;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;

  .suggestion-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #d48806;
    margin-bottom: 16rpx;
  }

  .suggestion-content {
    font-size: 26rpx;
    color: #ad6800;
    line-height: 1.5;
    margin-bottom: 20rpx;
  }

  .suggestion-action {
    background: #d48806;
    color: #ffffff;
    font-size: 26rpx;
    padding: 16rpx 32rpx;
    border-radius: 20rpx;
    text-align: center;
    display: inline-block;
  }
}

.history-card {
  background: #ffffff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

  .history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .history-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333333;
    }

    .clear-history {
      font-size: 26rpx;
      color: #74b9ff;
    }
  }

  .history-list {
    .history-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f5f5f5;

      &:last-child {
        border-bottom: none;
      }

      .history-content {
        flex: 1;
        font-size: 28rpx;
        color: #333333;
      }

      .history-time {
        font-size: 24rpx;
        color: #999999;
      }
    }
  }

  .history-empty {
    text-align: center;
    color: #999999;
    font-size: 28rpx;
    padding: 40rpx 0;
  }
}

.bottom-actions {
  display: flex;
  gap: 20rpx;
  padding: 0 10rpx;

  .action-btn {
    flex: 1;
    height: 100rpx;
    border-radius: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 16rpx;

    .btn-text {
      font-size: 30rpx;
      font-weight: 600;
    }

    &.secondary {
      background: #ffffff;
      border: 1rpx solid #e9ecef;

      .btn-text {
        color: #666666;
      }
    }

    &.primary {
      background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);

      .btn-text {
        color: #ffffff;
      }
    }
  }
}
</style>
